<template>
  <div>
    <div class="search">
      <div class="input">
        <p>
          <label>主子渠道：</label>
          <el-input placeholder="请输入ID" v-model="channelId" abel="条件"></el-input>
        </p>
        <p>
          <label>是否上架：</label>
          <el-select v-model="type" placeholder="请选择">
            <el-option
              v-for="(item,key) in typeList"
              :key="item.key"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>

        </p>
        <p>
          <el-button type="primary" class="se" style="margin-left:10px;" @click="search">搜索</el-button>
        </p>
      </div>
    </div>
    <div class="add">
      <el-button type="primary" @click="dialogs">新增</el-button>
      <el-button type="danger" @click="del">批量删除</el-button>
    </div>
    <tableVue
      :list="list"
      :state="true"
      v-loading="pagaData.loading"
      @changeData="selectionVal"
      :total="total"
      @sizeChange="handSize"
    >
      <slot>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="mini" @click="compile(scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              class="del"
              @click="handleEdit(scope.$index, scope.row,2)"
            >删除</el-button>
          </template>
        </el-table-column>
      </slot>
    </tableVue>
    <dialogVue title="操作轮播" :dialog="dialog" @close="changeData" :state="false">
      <slot>
        <el-form :model="pagaData" ref="ruleForm" label-width="120px" class="demo-ruleForm">
          <el-form-item label="渠道" prop="content">
            <el-cascader :options="lord" :props="defaults" v-model="selectedOptions"></el-cascader>
          </el-form-item>
          <el-form-item label="跳转地址" prop="content">
            <el-input v-model="pagaData.pageJumpUrl" placeholder="请输入跳转地址"></el-input>
          </el-form-item>
          <el-form-item label="排序" prop="content">
            <el-input v-model="pagaData.ordinal" placeholder="请输入排序"></el-input>
          </el-form-item>
          <el-form-item label="是否上架" prop="content">
            <el-select v-model="pagaData.value" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="content">
            <el-input v-model="pagaData.remark" type="textarea" placeholder="请输入备注"></el-input>
          </el-form-item>
          <el-form-item label="轮播图片" prop="content">
            <el-upload
              class="upload-demo"
              :auto-upload="false"
              :on-change="upload"
              :on-exceed="exceed"
              :limit="1"
              action="https://jsonplaceholder.typicode.com/posts/"
              :file-list="fileList2"
              :list-type="String"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
          <!-- *********************************************************************** -->
          <el-form-item label="是否分享" prop="content">
            <el-select v-model="pagaData.isShare" placeholder="请选择">
              <el-option label="是" value="Y"></el-option>
              <el-option label="否" value="N"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分享登录" prop="content">
            <el-select v-model="pagaData.isLogin" placeholder="请选择">
              <el-option label="是" value="Y"></el-option>
              <el-option label="否" value="N"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分享标题" prop="content">
            <el-input v-model="pagaData.shareTitle" placeholder="请输入分享标题"></el-input>
          </el-form-item>
          <el-form-item label="分享描述" prop="content">
            <el-input v-model="pagaData.shareDesc" type="textarea" placeholder="请输入分享描述"></el-input>
          </el-form-item>
          <!-- shareImage -->
          <el-form-item label="分享图片" prop="promotePrice">
            <el-upload
              ref="upload"
              :limit="1"
              :action="uploadingImg"
              :on-change="changeImgFile"
              :http-request="custom"
              :file-list="fileList"
              :on-exceed="exceed"
              :auto-upload="false"
              class="upload-demo"
              list-type="picture"
            >
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              <el-button
                style="margin-left: 10px;"
                size="small"
                type="success"
                @click="custom(0)"
              >上传到服务器</el-button>
            </el-upload>
          </el-form-item>

          <el-form-item label="分享链接" prop="content">
            <el-input v-model="pagaData.shareUrl" placeholder="请输入分享链接"></el-input>
          </el-form-item>
          <el-form-item class="confirm">
            <el-button type="primary" v-if="btnState == '1'" @click="submitForm('ruleForm')">创建</el-button>
            <el-button type="primary" v-if="btnState == '2'" @click="compileForm('ruleForm')">更新</el-button>
          </el-form-item>
        </el-form>
      </slot>
    </dialogVue>
  </div>
</template>

<script>
import Data from "./carouselData.js";
import dialogVue from "@/components/dialog.vue";
import tableVue from "@/components/alltable.vue";
import { Base64 } from "js-base64";
import checkPermission from "@/utils/permission"; // 权限判断函数
import {
  addCarousel,
  carouselList,
  delCarousel,
  allChannel,
  compileChannel
} from "@/api/carousel/carousel";
import { upLoadingImg } from "@/api/shoppingCentre/shoppingCentre";
export default {
  components: {
    tableVue,
    dialogVue
  },
  data() {
    return JSON.parse(JSON.stringify(Data));
  },
  mounted() {
    var data = {};
    this.getcarouselList(data);
    this.getChannel();
  },
  methods: {
    getChannel() {
      //获取子主渠道
      allChannel().then(res => {
        if (res.data.code == "OK") {
          this.lord = res.data.data;
        }
      });
    },
    selectionVal(val) {
      this.rowVal = val;
    },
    getcarouselList(data) {
      //获取轮播图列表
      this.pagaData.loading = true;
      if (JSON.stringify(data) == "{}") {
        data["current"] = "1";
        data["size"] = "10";
      }
      carouselList(data).then(res => {
        if (res.data.code == "OK") {
          this.pagaData.loading = false;
          this.list.tbody = res.data.data.records.map(item => {
            item.isOnline = item.isOnline == "Y" ? "是" : "否";
            item.gmtCreate = this.switchTime(item.gmtCreate);
            item.gmtUpdate = this.switchTime(item.gmtUpdate);
            return item;
          });
          this.total = res.data.data.total;
        } else {
          this.pagaData.loading = false;
        }
      });
    },
    dialogs() {
      if (checkPermission("cms_lbt_add") == true) {
        this.dialog = true;
        this.btnState = "1";
        this.pagaData = {};
        this.selectedOptions = [];
        this.fileList2 = [];
        this.fileList = [];
      } else {
        this.$message.error("您没有权限添加");
      }
    },
    changeData(val) {
      this.dialog = val;
    },
    handleEdit(idx, item, num) {
      if (num == 2) {
        this.del();
      } else {
        this.bannerId = item.bannerId;
      }
    },
    del() {
      if (checkPermission("cms_lbt_del") == true) {
        if (this.rowVal.length > 0) {
          this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              let id = "";
              this.rowVal.map(item => {
                id += item.bannerId + ",";
              });
              delCarousel(id).then(res => {
                if (res.data.code == "OK") {
                  this.$message.success("删除轮播成功");
                  var data = {};
                  this.getcarouselList();
                } else {
                  this.$message.error(res.data.data.errorMessage);
                }
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除"
              });
            });
        } else {
          this.$message.error("请选择你要删除的轮播");
        }
      } else {
        this.$message.error("您没有权限删除");
      }
    },

    submitForm() {
      let channelId = "";
      let childChannelId = "";
      this.selectedOptions.map((item, index) => {
        if (index == 0) {
          channelId = item;
        } else {
          childChannelId = item;
        }
      });
      let data = {
        channelId: channelId,
        childChannelId: childChannelId,
        pageImgUrl: this.pagaData.pageImgUrl,
        pageJumpUrl: this.pagaData.pageJumpUrl,
        isOnline: this.pagaData.value,
        ordinal: this.pagaData.ordinal,
        remark: this.pagaData.remark,
        isShare: this.pagaData.isShare, //是否分享
        shareTitle: this.pagaData.shareTitle, //分享标题
        shareDesc: this.pagaData.shareDesc, //分享描述
        shareImage: this.pagaData.shareImage, //分享图片
        shareUrl: this.pagaData.shareUrl, // 分享链接
        isLogin : this.pagaData.isLogin
      };
      if (!data.pageImgUrl) {
        this.$message.error("请上传轮播图片");
        return false;
      }
      if(data.isShare=='Y'){
        if(!data.shareImage){
          this.$message.error('请上传分享图片')
          return false
        }
      }
      addCarousel(data).then(res => {
        if (res.data.code == "OK") {
          this.$message.success("新增轮播成功");
          this.pagaData.dialog = false;
          this.dialog = false;
          let data = {};
          this.getcarouselList(data);
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    upload(file) {
      let reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = () => {
        this.pagaData.pageImgUrl = reader.result.split(",")[1];
      };
    },
    // 分享图片
    upload1(file) {
      let reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = () => {
        this.pagaData.shareImage = reader.result.split(",")[1];
      };
    },
    changeImgFile(file) {
      // 拿到单张图片的地址
      const reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = () => {
        this.imgData.base64Str = reader.result.split(",")[1];
        this.imgData.id = file.uid;
        this.imgData.fileOriginName = file.name;
        this.imgData.fileType = file.name.split(".")[1];
      };
    },
    custom(file) {
      if(!this.imgData.id){
        this.$message.error("请选择分享图片")
        return false
      }
      this.$message({
        showClose: true,
        message: "图片正常在上传请稍后.......",
        type: "warning"
      });
      var data = {
        base64Str: this.imgData.base64Str,
        fileOriginName: this.imgData.fileOriginName,
        fileType: this.imgData.fileType,
        id: this.imgData.id
      };
      upLoadingImg(data).then(res => {
        if (res.data.code == "OK") {
          this.$message.success("上传图片成功");
          this.pagaData.shareImage = res.data.data.fileURL;
          console.log(this.pagaData.shareImage);
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    compile(item) {
      //编辑

      if (checkPermission("cms_lbt_edit") == true) {
        var temp = {
          name: "",
          url: item.pageImgUrl
        };

        this.fileList2 = [];
        this.fileList = [];
        this.dialog = true;
        this.btnState = "2";
        this.selectedOptions.push(item.channelId, item.childChannelId);
        this.pagaData.pageJumpUrl = item.pageJumpUrl;
        this.pagaData.pageImgUrl = item.pageImgUrl;
        this.pagaData.ordinal = item.ordinal;
        this.pagaData.value = item.isOnline;
        this.pagaData.remark = item.remark;
        this.pagaData.bannerId = item.bannerId;
        this.pagaData.imgs = item.pageImgUrl;
        this.pagaData.isShare = item.isShare;
        this.pagaData.shareTitle = item.shareTitle;
        this.pagaData.shareDesc = item.shareDesc;
        this.pagaData.shareUrl = item.shareUrl;
        this.pagaData.isLogin = item.isLogin;
        this.pagaData.shareImage = item.shareImage;
        // console.log(item);
        this.fileList2.push(temp);
        this.fileList.push({ name: "", url: item.shareImage });
        // console.log(item);
      } else {
        this.$message.error("您没有权限编辑");
      }
    },
    compileForm() {

      let channelId = "";
      let childChannelId = "";
      this.selectedOptions.map((item, index) => {
        if (index == 0) {
          channelId = item;
        } else {
          childChannelId = item;
        }
      });
      let data = {
        channelId: channelId,
        childChannelId: childChannelId,
        pageImgUrl: this.pagaData.pageImgUrl,
        pageJumpUrl: this.pagaData.pageJumpUrl,

        ordinal: this.pagaData.ordinal,
        remark: this.pagaData.remark,
        bannerId: this.pagaData.bannerId,
        // *****************************************************************
        //是否分享
        isShare: this.pagaData.isShare,
        shareTitle: this.pagaData.shareTitle,
        shareImage: this.pagaData.shareImage,
        shareUrl: this.pagaData.shareUrl,
        isLogin : this.pagaData.isLogin,
        shareDesc : this.pagaData.shareDesc
      };
      if (this.pagaData.value == '否') {
          data['isOnline'] =  'N'
      } else {
        data['isOnline'] = 'Y'
      }
      compileChannel(data).then(res => {
        if (res.data.code == "OK") {
          this.$message.success("编辑轮播成功");
          this.dialog = false;
          let data = {};
          this.getcarouselList(data);
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    handSize(val) {
      let data = {
        isOnline: this.type,
        channelId: this.channelId,
        current: val,
        size: "10"
      };
      this.getcarouselList(data);
    },
    search() {
      this.pagaData.loading = true;
      let data = {
        isOnline: this.type,
        channelId: this.channelId
      };
      carouselList(data).then(res => {
        if (res.data.code == "OK") {
          this.pagaData.loading = false;
          this.$message.success("搜索成功");
          this.list.tbody = res.data.data.records.map(item => {
            item.isOnline = item.isOnline == "Y" ? "是" : "否";
            item.gmtCreate = this.switchTime(item.gmtCreate);
            item.gmtUpdate = this.switchTime(item.gmtUpdate);
            return item;
          });
          this.total = res.data.data.total;
        } else {
          this.pagaData.loading = false;
        }
      });
    },
    exceed(files, fileList) {
      this.$message.error("只能传一张图片");
    },
    exceed1(files, fileList) {
      this.$message.error("只能传一张图片");
    }
  }
};
</script>

<style scoped>
.search {
  width: 100%;
  background-color: #fff;
  padding: 20px;
  box-sizing: border-box;
  margin-top: 10px;
}
.input {
  /* width: 300px; */
  display: flex;
  flex-wrap: wrap;
}
.input p {
  margin-top: 10px;
}
label {
  line-height: 40px;
  color: #333;
  margin: 0 10px;
}
.el-input {
  width: 200px;
  height: 20px;
}
.add {
  margin-top: 10px;
  padding-left: 14px;
}
.se {
  margin-left: 20px;
}
.confirm {
  position: absolute;
  bottom: -1px;
  right: 100px;
}
</style>
